<template>
  <div class="Wft-Editor flex flex-col">
    <Toolbar
      class="default-border"
      :editor="editorRef"
      :mode="mode"
    />
    <Editor
      class="flex-1 overflow-y-auto"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="onChange"
    />
  </div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IDomEditor } from '@wangeditor/editor'
import { onBeforeUnmount, shallowRef, computed, watch } from 'vue'
 
type TProps = {
  mode?: string,
  valueHtml?: string,
  placeholder?: string,
  disable?: boolean
}
const props = withDefaults(defineProps<TProps>(), {
  mode: 'default', // or 'simple'
  valueHtml: '',
  placeholder: '请输入内容...',
  disable: false
})
type TEmits = {
  (e: 'update:valueHtml', params: string): void
  (e: 'update:valueText', params: string): void
  (e: 'onChange', params: IDomEditor): void
}
const emits = defineEmits<TEmits>()
 
const editorRef = shallowRef()
 
const valueHtml = computed({
  get() {
    return props.valueHtml
  },
  set(valueHtml) {
    emits('update:valueHtml', valueHtml)
  }
})
 
watch(() => props.disable, bool => {
  if(!editorRef.value) return
  bool ? (editorRef.value as IDomEditor).disable() : (editorRef.value as IDomEditor).enable()
}, { deep: true })
 
const editorConfig = computed(() => {
  return { placeholder: props.placeholder }
})
 
// 记录 editor 实例，重要！
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}
 
// editor 改变
const onChange = (editor: IDomEditor) => {
  emits('onChange', editor)
}
 
// 销毁编辑器
onBeforeUnmount(() => {
  if(!editorRef.value) return
  editorRef.value.destroy()
})
 
function getHtml() {
  return (editorRef.value as IDomEditor).getHtml()
}
function getText() {
  return (editorRef.value as IDomEditor).getText()
}
defineExpose({ getHtml, getText })
</script>
<style scoped>
.Wft-Editor {
  width: 100%;
  height: 100%;
}
.flex {
  display: flex;
}
 
.flex-col {
  flex-direction: column;
}
 
.default-border {
  border-bottom: 1px solid #ccc;
}
 
.flex-1 {
  flex: 1;
}
 
.overflow-y-auto {
  overflow-x: hidden;
  overflow-y: auto;
}
</style>